using DBLibrary;
using DBLibrary.HLBJMemoryTool;
using DevExpress.Xpo;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.OpenApi;
using Microsoft.Extensions.Logging;
using Server.Services;
using System.Configuration;

var builder = WebApplication.CreateBuilder(args);

// 配置服务器监听地址，确保可以从外网访问
builder.WebHost.ConfigureKestrel(options =>
{
    // 监听所有网络接口的5200端口
    options.ListenAnyIP(5200);
});

// 配置数据库连接
var configuration = builder.Configuration;

// Add services to the container.
builder.Services.AddControllers();

// 添加CORS支持，允许所有来源
// 注意：在生产环境中应该限制为特定的来源
builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowAllOrigins",
        policy =>
        {
            policy.AllowAnyOrigin()
                  .AllowAnyMethod()
                  .AllowAnyHeader();
        });
});
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
builder.Services.AddOpenApi();

// 注册XPO数据库连接 - 使用原始的注册方法
builder.Services.AddHLBJMemoryToolAsXpoDefaultSession(configuration);
builder.Services.AddHLBJMemoryToolUnitOfWork(configuration);

// 注册认证服务
builder.Services.AddScoped<IAuthService, AuthService>();

// 注册FTP服务
builder.Services.AddScoped<IFtpService, FtpService>();

var app = builder.Build();

// 数据库连接调试信息 - 简化版本，只获取工作单元但不执行查询
using (var scope = app.Services.CreateScope())
{
    var logger = scope.ServiceProvider.GetRequiredService<ILogger<Program>>();
    try
    {
        logger.LogInformation("尝试获取数据库工作单元...");
        var unitOfWork = scope.ServiceProvider.GetRequiredService<HLBJMemoryToolUnitOfWork>();
        logger.LogInformation("成功获取数据库工作单元");
        
        // 不执行实际查询，仅验证工作单元能够被正确解析
        logger.LogInformation("数据库工作单元已成功注入");
    }
    catch (Exception ex)
    {
        logger.LogError(ex, "数据库工作单元获取失败");
    }
}

// 全局异常处理中间件
app.UseExceptionHandler(errorApp =>
{
    errorApp.Run(async context =>
    {
        var exception = context.Features.Get<Microsoft.AspNetCore.Diagnostics.IExceptionHandlerFeature>()?.Error;
        if (exception != null)
        {
            var logger = context.RequestServices.GetRequiredService<ILogger<Program>>();
            logger.LogError(exception, "发生未处理的异常");

            // 设置响应状态码
            context.Response.StatusCode = StatusCodes.Status500InternalServerError;
            context.Response.ContentType = "application/json";

            // 返回错误信息
            var errorResponse = new
            {
                StatusCode = StatusCodes.Status500InternalServerError,
                Message = "服务器内部错误",
                Error = app.Environment.IsDevelopment() ? exception.Message : "处理请求时发生错误"
            };

            await context.Response.WriteAsJsonAsync(errorResponse);
        }
    });
});

// 使用CORS策略
app.UseCors("AllowAllOrigins");

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.MapOpenApi();
    
    // 添加Debug模式下的客户端连接日志
    app.Use(async (context, next) =>
    {
        var logger = context.RequestServices.GetRequiredService<ILogger<Program>>();
        logger.LogDebug("客户端连接: IP = {IpAddress}, 路径 = {Path}, 方法 = {Method}",
            context.Connection.RemoteIpAddress?.ToString(),
            context.Request.Path,
            context.Request.Method);
        
        await next();
    });
}

// 移除不需要的授权中间件，因为当前应用程序不使用复杂的认证机制
app.MapControllers();

app.Run();
